'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  //新增
  async put(){
      let {ctx,service} = this;
      let {title,status,important} = ctx.request.body;

      let readnum = Math.ceil(Math.random()*100);
      let author = 'sum';
      let timer = new Date();

      if(title && timer && status && important){
            try{
                await service.home.put(title,timer,status,important,readnum,author);

                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
      }else{
          ctx.body = {
              code:2,
              msg:'参数缺失'
          }
      }
  }

  //更新
  async update(){
    let {ctx,service} = this;
    let {title,status,important,id} = ctx.request.body;

    let readnum = Math.ceil(Math.random()*100);
    let author = 'sum';
    let timer = new Date();
    if(title && timer && status && important && id){
        try{
            await service.home.update(title,timer,status,important,readnum,author,id);

            ctx.body = {
                code:1,
                msg:'更新成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数缺失'
        }
    }

  }

  //查询
  async bookslist(){
      let {ctx,service} = this;
      let {start=0,limit=2} = ctx.query;
      try{
        let data = await service.home.bookslist(start,limit);

        let total = await service.home.total();
        console.log(total);
        ctx.body = {
            code:1,
            data,
            total:total[0]['count(*)']
        }
      }catch(e){
        ctx.body = {
            code:2,
            msg:e
        }
      }
  }

  //删除
  async del(){
      let {ctx,service} = this;
      let {id} = ctx.query;
      
      if(id){
        //token
        // let token = ctx.get('token');
        // let info = jwt.verify(token,'1705d');
        if(ctx.info.roleid === 1){
            //管理员
            try{
                await service.home.del(id);
                ctx.body = {
                    code:1,
                    msg:'删除成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            //普通用户
            ctx.body = {
                code:3,
                msg:'没有删除的权限'
            }
        }
      }else{
            ctx.body = {
                code:2,
                msg:'参数缺失'
            }
      }
  }
}

module.exports = HomeController;
